<script setup lang="ts" name="Counter">
import { ref, onUnmounted } from 'vue'
import { NCard, NButton, NSpace } from 'naive-ui'

const count = ref(0)
const isRunning = ref(false)
let timer: number | null = null

const toggleCounter = () => {
  if (isRunning.value) {
    stopCounter()
  } else {
    startCounter()
  }
}

const startCounter = () => {
  isRunning.value = true
  timer = window.setInterval(() => {
    count.value++
  }, 1000)
}

const stopCounter = () => {
  if (timer) {
    window.clearInterval(timer)
    timer = null
  }
  isRunning.value = false
}

const reset = () => {
  stopCounter()
  count.value = 0
}

onUnmounted(() => {
  if (timer) {
    window.clearInterval(timer)
  }
})
</script>

<template>
  <div class="max-w-md mx-auto">
    <NCard title="计数器">
      <NSpace vertical size="large">
        <!-- 计数显示 -->
        <div class="text-center">
          <div class="text-6xl font-bold mb-4 text-gray-600">
            {{ count }}
          </div>
        </div>

        <!-- 控制按钮 -->
        <div class="flex justify-center gap-4">
          <NButton type="primary" size="large" @click="toggleCounter">
            {{ isRunning ? '停止' : '开始' }}
          </NButton>
          <NButton type="warning" size="large" @click="reset" :disabled="count === 0">
            重置
          </NButton>
        </div>
      </NSpace>
    </NCard>
  </div>
</template>
>
